<template>
  <div>
    <div
        style="display: flex; justify-content: space-between; align-items: center; width: 100%; border-bottom: 2px solid #cccccc; padding-bottom: 10px">
      <span style="font-size: 17px; color: #333333;">广告详情</span>
      <i class="el-icon-back" @click="handleBack()"
         style="font-size: 18px; color: deepskyblue; cursor: pointer;">返回</i>
    </div>
    <div style="width: 100%">
      <table style="width: 100%;margin-left: 20px;">
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">ID</td>
          <td>{{ appAd.id.toString().padStart(9, '0') }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">广告标题<span style="color: red">*</span></td>
          <td>
            <el-input style="width: 500px" v-model="updateForm.adHeadline" v-if="this.appAd.isStatus !== 1"></el-input>
            <span v-if="this.appAd.isStatus === 1">{{ appAd.adHeadline }}</span>
          </td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">广告图片<span style="color: red">*</span></td>
          <td>
            <div>
              <div style="display: flex" v-if="this.appAd.isStatus !== 1">
                <el-upload drag
                           class="avatar-uploader el-upload--text"
                           :action="uploadUrl"
                           :multiple="false"
                           :show-file-list="true"
                           :on-success="onImgChineseSuccess"
                           :before-upload="beforeUploadImage"
                           :on-error="onFileError"
                >
                  <i v-if="updateForm.picChinese" class="el-icon-view"></i>
                  <i v-else class="el-icon-upload"></i>
                  <div v-if="updateForm.picChinese" style="width: 100%;height: 100%">
                    <img :src="updateForm.picChinese" class="avatar" style="width: 150px;height: 100%"/>
                  </div>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div class="el-upload__tip" slot="tip">
                    只能上传 JPEG/PNG/GIF/BMP/WebP 格式的图片，且不超过200MB
                  </div>
                </el-upload>
                <el-upload drag
                           class="avatar-uploader el-upload--text"
                           :action="uploadUrl"
                           :multiple="false"
                           :show-file-list="true"
                           :on-success="onImgEnglishSuccess"
                           :before-upload="beforeUploadImage"
                           :on-error="onFileError"
                >
                  <i v-if="updateForm.picEnglish" class="el-icon-view"></i>
                  <i v-else class="el-icon-upload"></i>
                  <div v-if="updateForm.picEnglish" style="width: 100%;height: 100%">
                    <img :src="updateForm.picEnglish" class="avatar" style="width: 150px;height: 100%"/>
                  </div>
                  <div class="el-upload__text">
                    将文件拖到此处，或<em>点击上传</em>
                  </div>
                  <div class="el-upload__tip" slot="tip">
                    只能上传 JPEG/PNG/GIF/BMP/WebP 格式的图片，且不超过200MB
                  </div>
                </el-upload>
              </div>
              <div style="display: flex; align-items: center;" v-if="this.appAd.isStatus === 1">
                <img :src="appAd.picChinese" alt="" style="width: 300px; height: 300px;">
                <img :src="appAd.picEnglish" alt="" style="width: 300px; height: 300px;">
              </div>
            </div>
          </td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">跳转链接<span style="color: red">*</span></td>
          <td>
            <el-input v-model="updateForm.imgUrl" style="width: 500px" v-if="this.appAd.isStatus !== 1"></el-input>
            <span v-if="this.appAd.isStatus === 1">{{ appAd.imgUrl }}</span>
          </td>
        </tr>
        <tr align="left" style="height: 50px" v-if="this.type == 2">
          <td style="width: 200px;">链接标题<span style="color: red">*</span></td>
          <td>
            <el-input v-model="updateForm.imgUrlTitle" style="width: 500px" v-if="this.appAd.isStatus !== 1"></el-input>
            <span v-if="this.appAd.isStatus === 1">{{ appAd.imgUrlTitle }}</span>
          </td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">状态</td>
          <td>
            {{ appAd.isStatus === 0 ? '已生效' : appAd.isStatus === 1 ? '已过期' : appAd.isStatus === 2 ? '已上架' : appAd.isStatus === 3 ? '已下架' : '未知' }}
          </td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">推送时间</td>
          <td>{{ formatOpenDateTime(appAd.upDateTime) }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;">失效时间</td>
          <td>{{ formatOpenDateTime(appAd.downDateTime) }}</td>
        </tr>
        <tr align="left" style="height: 50px">
          <td style="width: 200px;"></td>

          <td>
            <button v-if="this.appAd.isStatus !== 1" class="el-button el-button--primary" @click="submit()" style="width: 80px;height: 40px">保存</button>
            <button class="el-button el-button--text" @click="updateStatus(2)"
                    style="height: 40px;color: #33cd95;border: 1px solid #33cd95;width: 80px;"
                    v-if="this.appAd.isStatus === 3">上架
            </button>
            <button class="el-button el-button--primary" @click="updateUp=true"
                    style="height: 40px;width: 100px;"
                    v-if="this.appAd.isStatus !== 3 && this.appAd.isStatus !== 1">重新推送
            </button>
            <button class="el-button el-button--text" @click="updateStatus(3)"
                    style="height: 40px;color: #f56c6c;border: 1px solid #f56c6c;width: 80px;"
                    v-if="this.appAd.isStatus === 0 || this.appAd.isStatus === 2">下架
            </button>
            <button class="el-button el-button--text" @click="handleDelete()" v-if="this.appAd.isStatus === 1"
                    style="height: 40px;color: red;border: 1px solid #f56c6c;width: 80px;">删除
            </button>
          </td>
        </tr>
      </table>

      <!--重新推送操作-->
      <el-dialog title="提示" :visible.sync="updateUp" width="500px">
        <div align="left">
          <el-button icon="el-icon-info" type="text" style="color: black">您确定重新推送该广告吗? 请设置推送时间~
          </el-button>
          <div style="margin: 20px">
            <el-form :model="updateUpForm" ref="updateUpForm" :rules="updateUpFormRules">
              <el-form-item prop="upDateTime">
                <el-date-picker
                    v-model="updateUpForm.upDateTime"
                    type="datetime"
                    placeholder="选择日期时间">
                </el-date-picker>
              </el-form-item>
            </el-form>
          </div>
          <span style="color: lightgray;font-size: small">推送时间必须大于当前时间</span>
        </div>
        <div slot="footer" class="dialog-footer">
          <el-button type="primary" @click="newUp()">确 定</el-button>
          <el-button @click="updateUp = false; resetForm('updateUpForm')">取 消</el-button>
        </div>
      </el-dialog>
    </div>
  </div>
</template>

<script>
import {selectAppAdById, updateAppAds, updateStatus} from "@/api/ad/appAds"
import {serverUrl} from "@/utils/request";

export default {
  name: "AppAdDetail",
  data() {
    return {
      uploadUrl: serverUrl + "/ad/oss/uploadOneFile",
      attrs: {
        accept: '*' //接受文件类型
      },
      file:{
        name: '',
        size: 0,
      },
      updateUp: false,
      updateUpForm: {
        upDateTime: '',
      },
      id: '',
      type: '',
      appAd: {
        id: '',
        adHeadline: '',
        isStatus: '',
        upDateTime: '',
        downDateTime: '',
        picChinese: '',
        picEnglish: '',
        imgUrl: '',
        imgUrlTitle: ''
      },
      updateForm: {
        id: '',
        adHeadline: '',
        picChinese: '',
        picEnglish: '',
        imgUrl: '',
        imgUrlTitle:''
      },
      updateUpFormRules:{
        upDateTime: [
          {
            validator: (rule, value, callback) => {
              if (!value) {
                return callback(new Error('推送时间不能为空'));
              }
              const currentTime = new Date();
              currentTime.setHours(currentTime.getHours() + 1); // 可以设置为当前时间之后的时间，这里示例为当前时间1小时后
              if (value < currentTime) {
                callback(new Error('推送时间必须大于当前时间'));
              } else if (value > this.appAd.downDateTime) {
                callback(new Error('推送时间必须小于失效时间'));
              }else {
                callback();
              }
            },
            trigger: 'change'
          }
        ]
      },
    }
  },
  methods: {
    submit() {
      this.$confirm('确定要保存吗？', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(() => {
        if(this.type === 2){
          if (this.updateForm.imgUrlTitle === ''){
            this.$message({
              type: 'error',
              message: '请先填写链接标题!'
            });
            return;
          } else if (this.updateForm.imgUrlTitle.length === 0) {
            this.$message({
              type: 'error',
              message: '链接标题不能为空!'
            });
            return;
          } else if (this.updateForm.imgUrlTitle.length > 40) {
            this.$message({
              type: 'error',
             message: '链接标题长度不能超过40!'
           });
           return;
          }
        }
        if (this.updateForm.picChinese === '') {
          this.$message({
            type: 'error',
            message: '请先上传中文图片!'
          });
          return;
        }
        if (this.updateForm.picEnglish === '') {
          this.$message({
            type: 'error',
            message: '请先上传英文图片!'
          });
          return;
        }
        if (this.updateForm.adHeadline === '') {
          this.$message({
            type: 'error',
            message: '请先填写广告标题!'
          });
          return;
        } else if (this.updateForm.adHeadline.length === 0) {
          this.$message({
            type: 'error',
            message: '广告标题不能为空!'
          });
          return;
        } else if (this.updateForm.adHeadline.length > 40) {
          this.$message({
            type: 'error',
            message: '广告标题长度不能超过40!'
          });
        }
        this.updateForm.id = this.id;
        const validateUrl = (rule, value, callback) => {
          if (value === '') {
            callback(new Error('跳转链接不能为空'));
          } else if (!/^(https?:\/\/)?([a-zA-Z0-9.-]+(\.[a-zA-Z]{2,})+)(:[0-9]{1,5})?(\/[^\s]*)?$/.test(value)) {
            callback(new Error('请输入合法的URL地址'));
          } else {
            callback();
          }
        };
        let isValid = true;

        validateUrl(null, this.updateForm.imgUrl, (error) => {
          if (error) {
            isValid = false; // 设置为不合法
            this.$message({
              type: 'error',
              message: error.message // 显示错误信息
            });
          }
        });

        if (!isValid) {
          this.$message({
            type: 'error',
            message: '请输入合法的URL地址'
          });
          return; // 如果不合法，停止后续操作
        }
        updateAppAds(this.updateForm).then(result => {
          if (result.code === 200) {
            this.$message({
              type: 'success',
              message: '保存成功!'
            });
            this.$router.go(-1);
          } else {
            this.$message({
              type: 'error',
              message: result.msg
            });
          }
        })
      }).catch(() => {
        this.$message({
          type: 'info',
          message: '已取消保存'
        });
      });
    },
    /*重置表单*/
    resetForm(formName) {
      this.$refs[formName].resetFields();
    },
    /*重新推送*/
    newUp() {
      this.$refs.updateUpForm.validate((valid) => {
        if (valid) {
          const data = {
            id: this.id,
            upDateTime: this.updateUpForm.upDateTime,
            isStatus: 0
          }
          updateStatus(data).then(res => {
            if (res.code === 200) {
              this.$message({
                message: '操作成功',
                type: 'success'
              });
              this.updateUp = false;
              this.resetForm('updateUpForm');
              this.init();
            } else {
              this.$message({
                message: '操作失败',
                type: 'warning'
              });
            }
          }).catch(() => {
            this.$message({
              type: 'info',
              message: '已取消'
            });
          });
        } else {
          console.log('表单验证失败');
          return false;
        }
      });
    },
    init() {
      selectAppAdById(this.id).then(result => {
        this.appAd = result.data;
        if (this.appAd.isStatus !== 1) {
          this.updateForm.adHeadline = this.appAd.adHeadline;
          this.updateForm.picChinese = this.appAd.picChinese;
          this.updateForm.picEnglish = this.appAd.picEnglish;
          this.updateForm.imgUrl = this.appAd.imgUrl;
          this.updateForm.imgUrlTitle = this.appAd.imgUrlTitle;
        }
      }).catch(err => {
        console.log(err);
      })
    },
    updateStatus(val) {
      const data = {
        id: this.id,
        isStatus: val
      }
      updateStatus(data).then(result => {
        if (result.code === 200) {
          this.$message({
            message: '上架成功',
            type: 'success'
          })
          this.init();
        } else {
          this.$message({
            message: result.message,
            type: 'error'
          })
        }
      })
    },
    handleDelete(){
      const data = {
        id: this.id,
        isDel: 1
      }
      updateStatus(data).then(result => {
        if (result.code === 200) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.$router.go(-1);
        } else {
          this.$message({
            message: result.message,
            type: 'error'
          })
        }
      })
    },
    /*规范时间格式 年月日 时分秒*/
    formatOpenDateTime(date) {
      if (!date) return '--'; // 如果日期为空，则返回 '--'

      // 将日期转换为 Date 对象（如果是字符串的话）
      const d = date instanceof Date ? date : new Date(date);

      // 获取年月日时分秒
      const year = d.getFullYear();
      const month = (d.getMonth() + 1).toString().padStart(2, '0');
      const day = d.getDate().toString().padStart(2, '0');
      const hour = d.getHours().toString().padStart(2, '0');
      const minute = d.getMinutes().toString().padStart(2, '0');
      const second = d.getSeconds().toString().padStart(2, '0');

      // 返回格式化的日期时间字符串，例如 '2024-08-27 12:34:56'
      return `${year}-${month}-${day} ${hour}:${minute}:${second}`;
    },
    handleBack() {
      this.$router.go(-1);
    },
    /*上传失败*/
    onFileError(file) {
      console.log('error', file);
    },
    /*上传成功*/
    onImgChineseSuccess(response) {
      this.updateForm.picChinese = response;
    },
    onImgEnglishSuccess(response) {
      this.updateForm.picEnglish = response;
    },
    /*上传图片之前校验*/
    beforeUploadImage(file) {
      const validImageTypes = ['image/jpeg', 'image/png', 'image/gif', 'image/bmp', 'image/webp'];
      const isImage = validImageTypes.includes(file.type);
      if (!isImage) {
        this.$message.error('只能上传 JPEG/PNG/GIF/BMP/WebP 格式的图片!');
        return false;
      }
      // 校验文件大小，最大为200MB
      const isLt200M = file.size / 1024 / 1024 < 200;
      if (!isLt200M) {
        this.$message.error('图片大小不能超过 200MB!');
        return false;
      }
      return true; // 通过校验
    }
  },
  mounted() {
    this.id = this.$route.query.id
    this.type = this.$route.query.type
    this.init();
  },
  created() {
  },
}
</script>

<style scoped>

</style>
